from common_utils import pre_n_days
from db.mongo_utils import query
import pandas as pd
from pymongo import MongoClient

LOG_CLIENT =  MongoClient('mongodb://admin:kans123456@172.18.172.219:27017/?authSource=admin')

def get_abnormal(phone: str, date_str: str):
    redman_logs = LOG_CLIENT['logs']['redman_logs']
    abnormals = []
    for row in redman_logs.find({'phone': phone, 'asctime': {'$regex': date_str}}):
        if '24小时' in row['message']:
            abnormals.append(f"{row['asctime']}{row['message']}")
        if '0.5小时' in row['message']:
            abnormals.append(f"{row['asctime']}{row['message']}")
        if '有验证滑块' in row['message']:
            abnormals.append(f"{row['asctime']}{row['message']}")
    return abnormals


def get_browse_posts(phone: str, date_str: str):
    redman_logs = LOG_CLIENT['logs']['redman_logs']
    posts = redman_logs.find({'phone': phone, 'asctime': {'$regex': date_str}, 'is_commercial': False, 'message': {'$regex': '浏览并抓取链接内容'}})
    return len(list(posts))


def get_user_actions(user, n = 1):
    phone = user['_id']
    start_date = f'{pre_n_days(n)} 00:00:00'
    end_date = f'{pre_n_days(n)} 23:59:59'
    data = {
        '手机号': user['_id'],
        '昵称': user.get('user_name'),
        '博主类型': user.get('account_type'),
        '关注数': user.get('attent_number'),
        '粉丝数': user.get('follow_number'),
        '获赞收藏数': user.get('collection_like'),
        '浏览量': 0,
        '评论量': 0,
        '点赞量': 0,
        '发贴量': 0,
        '状态备注': user.get('login_remark')
    }
    # 判断注册时间是否在2025-03-01之后
    registration_time = user.get('registration_time')
    if registration_time:
        try:
            reg_date = pd.to_datetime(registration_time)
            target_date = pd.to_datetime('2025-03-01')
            data['注册时间'] = registration_time
            data['是否是新号'] = '是' if reg_date >= target_date else '否'
        except:
            data['注册时间'] = registration_time
            data['是否是新号'] = '未知'
    else:
        data['注册时间'] = '无'
        data['是否是新号'] = '未知'
    for row in query('data_works', 'redbook_actions', {'created_at': {'$gte': start_date, '$lte': end_date}, 'phone': phone, 'is_commercial': {'$ne': True}}):
        # data['浏览量'] = data['浏览量'] + 1
        if 'make_comment' == row['action']:
            data['评论量'] = data['评论量'] + 1
        if 'click_like' == row['action']:
            data['点赞量'] = data['点赞量'] + 1
        if 'publish' in row['action']:
            data['发贴量'] = data['发贴量'] + 1
    
    if user.get('is_banned'):
        data['当前状态是否异常'] = '是'
    else:
        data['当前状态是否异常'] = '否'
    data['日期'] = pre_n_days(n)
    data['浏览量'] = get_browse_posts(phone, pre_n_days(n))
    data['vm'] =  user.get('vm')
    return data
    


def get_user_base_info():
    user_list = []
    n = 2
    for n in range(1, n):
        for user in query('data_works', 'redbook_user_info'):
            all_data = get_user_actions(user, n)
            user_list.append(all_data)
    df = pd.DataFrame(user_list)
    df.to_excel(f'非商业-小红书自养号行为日志{pre_n_days(n)}~{pre_n_days(0)}.xlsx', index=False)




if __name__ == '__main__':
    get_user_base_info()
